package com.tpfinal.agenda.model.factories;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;

import com.tpfinal.agenda.core.mysqlrequests.MySQL;
import com.tpfinal.agenda.model.City;
import com.tpfinal.agenda.model.Company;
import com.tpfinal.agenda.model.Contact;
import com.tpfinal.agenda.model.Person;

public class ContactsFactory {

	public static final ArrayList<Contact> createContactListFromMySqlResult(
			ResultSet data) {

		ArrayList<Contact> list = new ArrayList<Contact>();

		try {
			while (data.next()) {

				Contact c = null;

				int id = data.getInt(MySQL.MYSQL_COLUMN_ID);
				String name = data.getString(MySQL.MYSQL_COLUMN_NOMBRE_RAZON);
				String address = data.getString(MySQL.MYSQL_COLUMN_DIRECCION);
				int phone = data.getInt(MySQL.MYSQL_COLUMN_TELEFONO);
				String email = data.getString(MySQL.MYSQL_COLUMN_EMAIL);

				City cityInfo = CitiesFactory.createCity(data);

				if (MySQL.MYSQL_CONTACT_TYPE_PERSON.equalsIgnoreCase(data
						.getString(MySQL.MYSQL_COLUMN_TIPO))) {

					Date birthday = data
							.getDate(MySQL.MYSQL_COLUMN_FECHA_NACIMIENTO);
					int cellphone = data
							.getInt(MySQL.MYSQL_COLUMN_TELEFONO_MOVIL);

					c = new Person(id, name, address, phone, email, birthday,
							cellphone, cityInfo);

				} else if (MySQL.MYSQL_CONTACT_TYPE_COMPANY
						.equalsIgnoreCase(data
								.getString(MySQL.MYSQL_COLUMN_TIPO))) {

					String url = data.getString(MySQL.MYSQL_COLUMN_WEB);
					String businessSector = data
							.getString(MySQL.MYSQL_COLUMN_RUBROS);

					c = new Company(id, name, address, phone, email, url,
							businessSector, cityInfo);
				}

				list.add(c);

			}
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}

		return list;

	}

}
